<!-- 照片裁剪 -->
<template>
	<el-dialog v-model="display" title="裁剪图片" width="80%" :append-to-body="true">
		<div>
			<vue-picture-cropper :boxStyle="{
					width: '100%',
					height: '100%',
					maxHeight:'60vh',
					backgroundColor: '#f8f8f8',
					margin: 'auto'
				}" :img="pic" :options="options" :key="num" />
		</div>
		<div class="flex c1">
			<el-button @click="options.aspectRatio = 500/281;num++">500:281</el-button>
			<el-button @click="options.aspectRatio = 1/1;num++">1:1</el-button>
			<el-button @click="clearCropper">不裁剪</el-button>
			<el-button @click="display = false">关闭</el-button>
			<el-button type="primary" @click="successImg()">确定</el-button>
		</div>
	</el-dialog>
</template>

<script setup>
	import VuePictureCropper, { cropper } from 'vue-picture-cropper/dist/esm'
	import upImg from "@/hook/upimg.js";
	const { upFile } = upImg('other'); //获取上传配置
	const emit = defineEmits(["img", 'update:show'])
	const props = defineProps({
		//是否显示弹窗
		show: {
			type: Boolean,
			default: false
		},
		//需要上传的空间名称
		name: {
			type: String,
			default: ''
		},
		//需要裁剪的图片
		pic: {
			type: String,
			default: ''
		}
	})

	const  clearCropper = (() => {
		cropper.clear()
	})

	const num = ref(1)

	const options = ref({
		viewMode: 1,
		dragMode: 'crop',
		aspectRatio: 1 / 1,
	})

	const base64 = ref('');

	const display = ref(true);

	watch(props, (newVal, oldVal) => {
		display.value = newVal.show;
		if (newVal.aspectRatio) options.value.aspectRatio = newVal.aspectRatio;
	}, { immediate: true })

	watch(display, (newVal, oldVal) => {
		emit('update:show', newVal)
	}, { immediate: true })


	//确定图片 获取裁切结果
	const api = inject('api');
	const successImg = (type) => {
		base64.value = cropper.getDataURL({
			fillColor:"transparent"
		})
		if(props.name == 'local'){
			api.post('api/img/imgBase64ToFile',{img:base64.value}).then(res=>{
				emit("img", { value: res.data, name: props.name })
				emit('update:show', false)
			})

		}else{
			upFile(props.name, base64.value, (v => {
				emit("img", { value: v.key, name: props.name })
				emit('update:show', false)
			}));
		}

	}
</script>

<style scoped lang="scss">
	.c1 {
		justify-content: flex-end;
		margin-top: 10px;
	}

	.c1 .a-but {
		margin-left: 20px;
	}
</style>